// useSpeech.ts
import { ref } from 'vue'

export function useSpeech() {
  const isSpeaking = ref(false)
  const supported = 'speechSynthesis' in window && 'SpeechSynthesisUtterance' in window

  let utterance: SpeechSynthesisUtterance | null = null

  const speak = (text: string, lang = 'zh-CN') => {
    if (!supported) {
      console.warn('当前浏览器不支持语音合成 (Web Speech API)')
      return
    }

    if (isSpeaking.value) {
      stop() // 如果正在播报，先中断
    }

    utterance = new SpeechSynthesisUtterance(text)
    utterance.lang = lang
    utterance.pitch = 1
    utterance.rate = 1
    utterance.volume = 1

    utterance.onstart = () => (isSpeaking.value = true)
    utterance.onend = () => (isSpeaking.value = false)
    utterance.onerror = () => (isSpeaking.value = false)

    window.speechSynthesis.speak(utterance)
  }

  const stop = () => {
    if (supported && window.speechSynthesis.speaking) {
      window.speechSynthesis.cancel()
      isSpeaking.value = false
    }
  }

  return {
    supported,
    isSpeaking,
    speak,
    stop,
  }
}
